<?php namespace Common\Model;
use Hdphp\Model\Model;

//商品属性表
use Common\Model\GoodsAttr;
use Common\Model\Detail;
class Goods extends Model{
//指定表名
    protected $table = "goods";
//  错误提示    
    protected $validate = array(
        array('shopname','required','商品名称不能为空',3,3),
        array('shopprice','required','商场价格不能为空',3,3)
    );
	
	protected $auto =array(
		array('time','time','function',3,1),
		array('admin_uid','aid','method',3,1),
		array('gnumber','time','function',3,1)
	);
	
//	获取用户ID
	public function aid(){
	    return $_SESSION['info']['aid'];
	}
	
	
	
	
	
//  添加商品--
    public function store(){
        if(!$this->create()) return FALSE;
		//添加商品第一张表，返回自增id
//		p(Q("post."));exit;
		$gid = $this->add();

		//添加货品列表
		$detailModel = new Detail();
		$detailModel->stores($gid);
		//属性添加
//		p(Q("post."));exit;


		//添加商品属性表
		$goodsAttrModel = new GoodsAttr();
		foreach (Q('post.attr') as $taid =>$v ) {
			if($v){
				$data = array(
					'gtvalue'=>$v,
					'type_attr_taid'=>$taid,
					'goods_aid'=>$gid
				);
//				p($data);exit;
				
				$goodsAttrModel->add($data);
			}
		}
		//规格添加--
		$spec = Q('post.spec');
		if($spec){
			$value = $spec['value'];
			foreach($value as $taid =>$v){
				foreach ($v as $kk =>$vv){
					$data = array(
						'gtvalue'=>$vv,
						'type_attr_taid'=>$taid,
						'goods_aid'=>$gid,
						'added'=>$spec['added'][$taid][$kk]
					);
					$goodsAttrModel->add($data);
				}
			}
			
		}

        return TRUE;
    }
	
	public function edit(){
	    if(!$this->create()) return FALSE;
			
			if(Q('post.pic')){
				if(Q('post.oldpic')){
					$oldpic =Q('post.oldpic');
					$img = pathinfo($oldpic);
					$thumb = str_replace('.'.$img['extension'],'_thumb.'.$img['extension'] , $oldpic);
					
					unlink($oldpic);
					
					unlink($thumb);
				}
			}else{
				$this->data['pic']= Q('post.oldpic');
			}
		
		
		$this->save();
		$aid = Q('post.aid',0,'intval');
		$DetailModel = new Detail();
		$DetailData = $DetailModel->edits($aid);
//		exit;
		Db::table("goods_attr")->where("goods_aid={$aid}")->delete();
		
//		p(Q("post."));exit;
				//添加商品属性表
		$goodsAttrModel = new GoodsAttr();
		foreach (Q('post.attr') as $taid =>$v ) {
			if($v){
				$data = array(
					'gtvalue'=>$v,
					'type_attr_taid'=>$taid,
					'goods_aid'=>$aid
				);
//				p($data);exit;
				
				$goodsAttrModel->add($data);
			}
		}
		//规格添加--
		$spec = Q('post.spec');
		if($spec){
			$value = $spec['value'];
			foreach($value as $taid =>$v){
				foreach ($v as $kk =>$vv){
					$data = array(
						'gtvalue'=>$vv,
						'type_attr_taid'=>$taid,
						'goods_aid'=>$aid,
						'added'=>$spec['added'][$taid][$kk]
					);
					$goodsAttrModel->add($data);
				}
			}
			
		}
		
		
		
		
		
		return TRUE;
	}
	
	
	
	
	 
}